package com.zeropoint.demo.interceptors;

import com.zeropoint.demo.mapper.UserMapper;
import com.zeropoint.demo.pojo.UserPO;
import com.zeropoint.demo.util.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /* //业务拦截相关规则
        Subject subject = SecurityUtils.getSubject();
        if(subject == null){
            return false;
        }

        // 获取 token ，解析出 user 对象放入到 request 种
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        if(token == null || token.length() == 0){
            return false;
        }
        String username = JwtUtil.getClaim(token);*/
        String username = (String) request.getAttribute("username");
        UserPO user = userMapper.getUserByName(username);
        request.setAttribute("user",user);

        //需要返回true，否则请求不会被控制器处理
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //log.info("请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后），如果异常发生，则该方法不会被调用");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //log.info("在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
